package demoserver;


import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author thien
 */
public class Queue implements Runnable {
    Vector queue = new Vector();
    private Thread thread;
    private long delay = 150;
    private DataOutputStream dataOutputStream;
    public Queue(DataOutputStream dataOutputStream){
        this.dataOutputStream = dataOutputStream;
        start();
    }

    public void addData(byte[] b){
        queue.addElement(b);
    }
    private void start(){
        thread = new Thread(this);
        thread.start();
    }
    
    public void close(){
        thread = null;
        try {
            dataOutputStream.close();
        } catch (IOException ex) {
            Logger.getLogger(Queue.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void run() {
        Thread currentThread = Thread.currentThread();
        while(currentThread == thread){
            long startTime = System.currentTimeMillis();
            if(queue.size()>0){
                try {
                    byte[] b = (byte[])queue.firstElement();
                    dataOutputStream.write(b);
                    dataOutputStream.flush();
                    queue.removeElementAt(0);

                } catch (IOException ex) {
                    Logger.getLogger(Queue.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            long timeTake = System.currentTimeMillis() - startTime;
            if(timeTake < delay){
                synchronized(this){
                    try {
                        wait(delay - timeTake);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
            else {
                    Thread.yield();
            }
        }
    }




    
}
